package com.demo.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

/**
 * ResourceServerConfig
 *
 * @author liujin
 * @date 2020/12/6 20:28
 */
@Configuration
@EnableConfigurationProperties(AccessProperties.class)
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    @Resource
    private AccessProperties accessProperties;

    @Resource
    private TokenStore tokenStore;

    @Resource
    private SecurityExpressionHandler expressionHandler;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources){
        resources.tokenStore(tokenStore).resourceId("resource_web")
                .stateless(true).expressionHandler(expressionHandler);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers(accessProperties.getUrls()).permitAll()
                .anyRequest().access("#accessService.hasPermission(request, authentication)");
    }
}
